#!/bin/bash

# 热点追踪系统 Docker 部署脚本
echo "🚀 开始部署热点追踪系统..."

# 检查 Docker 和 Docker Compose
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down

# 清理旧镜像（可选）
read -p "是否清理旧的Docker镜像？(y/N): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🧹 清理旧镜像..."
    docker system prune -f
fi

# 构建并启动服务
echo "🔨 构建并启动服务..."
docker-compose up --build -d

# 等待服务启动
echo "⏳ 等待服务启动..."
sleep 30

# 检查服务状态
echo "📋 检查服务状态..."
docker-compose ps

# 检查健康状态
echo "🏥 检查服务健康状态..."
echo "Redis: $(docker-compose exec redis redis-cli ping 2>/dev/null || echo 'FAILED')"
echo "API: $(curl -s http://localhost:3001/api/health 2>/dev/null | grep -o 'healthy' || echo 'FAILED')"
echo "Frontend: $(curl -s http://localhost/health 2>/dev/null | grep -o 'healthy' || echo 'FAILED')"

echo "✅ 部署完成！"
echo "🌐 访问地址: http://localhost"
echo "📊 API地址: http://localhost:3001/api"
echo "📝 查看日志: docker-compose logs -f"